let fs = require('fs')
let os = require('os')
let url = require('url')
let http = require('http')
let path = require('path')
let promisify = require('util').promisify
let mime = require('mime-types')

/**
 * 默认值配置
 */
let defaults = {
  mime: {
    html: 'text/html; charset=utf-8'
  },
  // 读取 pathname 对应本地目录返回的类型
  type: {
    FILE: 'file',
    NOT_FOUND: '404',
    DIRECTORY: 'directory'
  }
}

let { mime: defaultMimeMap, type: defaultTypeMap } = defaults

let cwd = process.cwd()

let exists = promisify(fs.exists)

main()

function main() {
  // ...
}






























// url-resolver
let resolver = {
  resolve: () => {
    //
  }
}

// fs-reader
let reader = {
  /**
   * @return {object}
   * //
   */
  read: async () => {
  }
}

// transformer
let transformer = {
  transform: async () => {
  }
}

// renderer
let renderer = {
  render: () => {
  },

  renderDirectory: () => {

  },

  renderToHtmlTpl: ({ title = '', nav = '', content = '' } = {}) => {
    return `
      <html>
        <head>
          <meta charset="utf-8" />
          <meta
            name="viewport"
            content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
          />
          <title>directory ${title}</title>
          <link rel="stylesheet" href="/src/assets/style.css" />
          <link rel="stylesheet" href="/src/assets/icon.css" />
        </head>
        <body class="directory">
          ${nav}
          ${content}
        </body>
      </html>
    `
  }
}

function createPathList(pathname, { isVdActived, vd }) {
  let pathList = pathname.split('/')
    .filter(Boolean)
    .map(_ => '/' + _)
    .map(mapValue)
    .map(item => {
      let { href } = item
      return {
        ...item,
        relativePath: href,
        href: isVdActived ? path.join(vd, href) : href
      }
    })
  
  // 去首页path链接对象
  pathList.unshift({
    name: '~',
    href: isVdActived ? path.join(vd, '/') : '/'
  })

  pathList = pathList.map((item, index, array) => {
    if (index === array.length - 1) {
      return {
        ...item,
        href: 'javascript:;'
      }
    }

    return item
  })

  return pathList
}

function mapValue(value, index, array) {
  let href = value
  for (let i = index - 1; i >= 0; i--) {
    href = array[i] + href
  }
  return { href, name: value.slice(1) }
}

/**
 * 打开默认浏览器
 */
function openBrowser(url) {
  let command = 'open'
  let osType = os.type()
  if (osType === 'Linux') {
    command = 'x-www-browser'
  } else if (osType === 'Windows_NT') {
    command = 'start'
  }
  exec(`${command} ${url}`)
}
